﻿using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;

using VIT.Library;
using VIT.Library.Web;
using VIT.Library.Images;
using VIT.DataHelper.DataAccess;
using VIT.Web.Controls;
using VIT.Wedding;
using VIT.Web.UI;


namespace VIT.Web.Admin
{
    public partial class ProductEdit : VIT.Web.UI.VITComponent
    {
        public string genOption = string.Empty;
        Provider.Product obj;

        protected new void Page_PreInit(Object sender, System.EventArgs e)
        {
            base.Page_PreInit(sender, e);
            LoadModule(SkinImages, "ProductImage", new Dictionary<string, string>());
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            obj = new Provider.Product();
            try
            {
                obj.Id = int.Parse(Request["sId"]);
            }
            catch
            {
                if (!IsPostBack)
                {
                    DateTime now = DateTime.Now;
                    string token = Convert.ToString(now.DayOfYear) + Convert.ToString(now.Minute) + Convert.ToString(now.Second);
                    int tokenInt = -Convert.ToInt32(token);
                    Session["sId_ProductImage"] = tokenInt;
                }
                obj.Id = 0;
            }

            if (obj.Id == 0) ButtonInsert.Visible = true; else ButtonModify.Visible = true;

            
            loadLanguages();
            loadManufacturers();
            loadSuppliers();

            loadData();
            loadCategory();

            loadProductType(obj.Id);
        }

        #region Methods
        private void loadData()
        {
            obj.LanguageId = Session["language"].ToString();
            obj.GetSingle();

            if (obj.Id > 0)
            {
                lblId.Text = obj.Id.ToString();
                trId.Visible = true;
                txtTitle.Text = obj.Title;
                txtBrief.Value = obj.Brief;
                txtContents.Value = obj.Description;
                Tag.Text = obj.Tag;
                if (obj.SupplierId != 0) ddlNCC.SelectedValue = obj.SupplierId.ToString();
                if (obj.ManufacturerId != 0) ddlNSX.SelectedValue = obj.ManufacturerId.ToString();
                txtPrice.Text = obj.Price.ToString();
                txtSale.Text = obj.Sale.ToString();
                Orders.Text = obj.Orders.ToString();
                Published.Checked = obj.Published;
                if (!string.IsNullOrEmpty(obj.Image))
                {
                    img.Visible = true;
                    img.ImageUrl = "~/Uploads/Images/Products/Details/" + obj.Image;
                    img.AlternateText = obj.Image;
                }

                var objProduct = VITData.GetObject<Product>(c => c.Id == obj.Id);
                if (objProduct != null)
                {
                    LoadColors(objProduct.Color ?? "");
                    LoadStyles(objProduct.Style ?? "");
                }
            }
            else // thêm mới
            {
                LoadColors();
                LoadStyles();
            }
        }

        private void loadProductType(int id)
        {
            Provider.ProductType at = new Provider.ProductType();
            at.LanguageId = obj.LanguageId;
            DataTable dt = at.GetAll();
            ListItem li;
            ProductType.Items.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                li = new ListItem(dr["Title"].ToString(), dr["Id"].ToString());
                if (id > 0) if (obj.hasType(dr["Id"].ToString())) li.Selected = true;
                ProductType.Items.Add(li);
            }

            //ProductType at = new ProductType();
            //at.LanguageId = Session["language"].ToString();
            //DataTable dt = at.GetAll();
            //dt.Columns.Add("Checked");            

            //for (int i=0; i< dt.Rows.Count; i++)
            //{
            //    if (id > 0) if (obj.hasType(dt.Rows[i]["Id"].ToString())) dt.Rows[i]["Checked"] = "checked";
            //}
            //rptTypes.DataSource = dt;
            //rptTypes.DataBind();
        }

        private void loadLanguages()
        {
            LanguageId.DataSource = new VIT.Provider.Language().getAll();
            LanguageId.DataTextField = "Name";
            LanguageId.DataValueField = "Id";
            LanguageId.DataBind();

            LanguageId.SelectedValue = Session["language"].ToString();
        }

        private void loadCategory()
        {
            Provider.Category cat = new Provider.Category();
            cat.LanguageId = Session["language"].ToString();
            this.genOption = cat.GetAll().GenTagOption("Id", "Title", "0", selected: obj.CategoryId.ToString());
        }

        private void loadManufacturers(int selected = 0)
        {
            Provider.ProductManufacturers m = new Provider.ProductManufacturers();
            var lstItem = m.GetAll();

            ddlNSX.Items.Clear();
            //ddlNSX.Items.Add(new ListItem("Tất cả", "0"));
            foreach (DataRow row in lstItem.Rows)
            {
                ddlNSX.Items.Add(new ListItem(row["Name"].ToString(), row["Id"].ToString()));
            }

            ddlNSX.SelectedIndex = selected;
        }

        private void loadSuppliers(int selected = 0)
        {
            Provider.ProductSupplier p = new Provider.ProductSupplier();
            var lstItem = p.GetAll();

            ddlNCC.Items.Clear();
            //ddlNCC.Items.Add(new ListItem("Tất cả", "0"));
            foreach (DataRow row in lstItem.Rows)
            {
                ddlNCC.Items.Add(new ListItem(row["Name"].ToString(), row["Id"].ToString()));
            }

            ddlNCC.SelectedIndex = selected;
        }


        private string check(int Id, string name, string ListId, string group)
        {
            string check = string.Empty;
            var lstId = ListId.Split(',').ToList<string>();
            if (lstId.Contains(Id.ToString())) check = "checked='true'";
            return String.Format("<input type='checkbox' {0} name='{1}' value='{2}'/> {3}", check, group, Id, name);
        }
        private void LoadColors(string ListColor = "")
        {
            var dtColor = VITData.GetQuery<Product_Color>().ToArray();
            StringBuilder str = new StringBuilder();
            foreach (var item in dtColor)
            {
                str.Append("<div style='textalign:left;margin:0 20px'>");
                str.Append(check(item.Id, item.Name, ListColor, "lstColor"));
                str.Append("</div>");  
            }
            lblColor.Text = str.ToString();
        }
        private void LoadStyles(string ListStyle = "")
        {
            var dtType = VITData.GetQuery<Product_Style>().ToArray();
            StringBuilder str = new StringBuilder();
            foreach (var item in dtType)
            {
                str.Append("<div style='textalign:left;margin:0 20px'>");
                str.Append(check(item.Id, item.Name, ListStyle, "lstStyle"));
                str.Append("</div>");
            }
            lblStyle.Text = str.ToString();
        }

        private void save()
        {
            var data = new Dictionary<dynamic, List<object>> {
                                                        {txtTitle, new List<object> {"required"}},
                                                        {Orders, new List<object> {"number"}}
                                                    };
            if (MainCore.checkData(data))
            {
                bool imgvalid = true;
                if (fupImg.HasFile)
                {
                    if (MainCore.checkFile(fupImg.FileName, "isImage"))
                    {
                        string oldImg = img.AlternateText;
                        obj.Image = String.Format("{0:yyMMddhhmmss}", DateTime.Now) + System.IO.Path.GetExtension(fupImg.FileName);
                        try
                        {
                            // save
                            fupImg.SaveAs(URLBaseDir + "Uploads/Images/Products/Details/" + obj.Image);
                            new ResizeImage().Resize(URLBaseDir + "/Uploads/Images/Products/Details/" + obj.Image, URLBaseDir + "/Uploads/Images/Products/Thumbs/" + obj.Image, 150);

                            // delete
                            if (System.IO.File.Exists(URLBaseDir + "Uploads/Images/Products/Details/" + oldImg))
                                System.IO.File.Delete(URLBaseDir + "Uploads/Images/Products/Details/" + oldImg);
                            if (System.IO.File.Exists(URLBaseDir + "Uploads/Images/Products/Thumbs/" + oldImg))
                                System.IO.File.Delete(URLBaseDir + "Uploads/Images/Products/Thumbs/" + oldImg);
                        }
                        catch (System.NotSupportedException ex)
                        {
                            throw ex;
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    else
                    {
                        imgvalid = false;
                        setTrueVisible(lblHinhKoDung);
                    }
                }
                else obj.Image = img.AlternateText;

                if (imgvalid)
                {
                    obj.CategoryId = Convert.ToInt32(Request["CategoryId"]);
                    obj.LanguageId = LanguageId.SelectedValue;
                    obj.Title = txtTitle.Text;
                    obj.Brief = txtBrief.Value;
                    obj.Description = txtContents.Value;
                    obj.Price = Convert.ToDecimal(txtPrice.Text);
                    obj.Sale = Convert.ToDecimal(txtSale.Text);
                    obj.SupplierId = Convert.ToInt32(ddlNCC.SelectedValue);
                    obj.ManufacturerId = Convert.ToInt32(ddlNSX.SelectedValue);
                    obj.Color = Request["lstColor"];
                    obj.Style = Request["lstStyle"];
                    obj.Tag = Tag.Text;
                    if (Orders.Text != "")
                        obj.Orders = int.Parse(Orders.Text);
                    obj.Published = Published.Checked;
                    //obj.Type = Request["ProductType"];                    
                    for (int i = 0; i < ProductType.Items.Count; i++)
                    {
                        if (ProductType.Items[i].Selected)
                        {
                            obj.Type += ProductType.Items[i].Value + ",";
                        }
                    }
                    if (obj.Save()) setTrueVisible(lblThanhCong);
                    else setTrueVisible(lblThatBai);
                }
            }
            else setTrueVisible(lblThatBai);
        }

        private void setTrueVisible(System.Web.UI.HtmlControls.HtmlGenericControl control)
        {
            lblThanhCong.Visible = false;
            lblThatBai.Visible = false;
            lblHinhKoDung.Visible = false;
            control.Visible = true;
        }
        #endregion

        #region
        protected void Save_Click(object sender, EventArgs e)
        {
            save();
            RedirectComponent("Product", "ProductList");
        }

        protected void Apply_Click(object sender, EventArgs e)
        {
            save();
            loadData();
            loadCategory();
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            RedirectComponent("Product", "ProductList");
        }

        protected void LanguageId_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["language"] = LanguageId.SelectedValue;
            loadData();
            loadCategory();
        }
        #endregion
    }
}